<?php
/**
 * Created by PhpStorm.
 * User: liuxiaojie
 * Date: 2019-02-24
 * Time: 12:15
 */

namespace app\mall\service;

use app\exception\CustomException;
use app\model\Company;
use app\model\CompanyAdmin;
use app\model\Coupon;
use app\model\Customer;
use app\model\DeliveryAddress;
use app\model\Goods;
use app\model\MoneyLog;
use app\model\MyCoupon;
use app\model\Order;
use app\model\Prize;
use app\model\PrizeLog;
use app\tools\Helper;
use app\tools\Log;
use app\tools\MIniprogram;
use app\tools\Wx;
use app\tools\Wxpay;
use think\Db;
use think\Exception;

class OrdersService extends BaseService{
    // 获取商品信息

    function goods($param = []){

        $where['sale'] = 1;
        $where['goods_id'] = $param['goods_id'];

        $data = Goods::where($where)->field("goods_id, name, cover, tiger_tee, price, fee, num as stock, address, sponsor, is_limit, type, coupon_id, uid, add_money, add_tiger")->find();
        if(!$data){
            throw new CustomException("GOODS_PULLED");
        }

        if($data['stock'] < $param['num'])
        {
            throw new CustomException("GOODS_STOCK_NOT_ENOUGH");
        }

        $result = $data;
        $result['num'] = $param['num'];
        $result['pay_price'] = $result['price']*$param['num'];
        $result['pay_tiger_tee'] = $result['tiger_tee']*$param['num'];
        $result['pay'] = $result['pay_price'] + $result['fee'];
        $address = DeliveryAddress::where(['customer_id'=> $param['customer_id']])->field('tel, address')->find();
        $result['address_info'] = $address;

        return $result;

    }

    function confirm($param = [])
    {

        Db::startTrans();

        try{

            $goods_info = Goods::where(['goods_id'=> $param['goods_id']])->field('is_limit_buy, limit_buy_time, limit_buy_num, is_time, end_time')->find();
            if($goods_info['is_time'] && strtotime($goods_info['end_time']) < time())
            {
                throw new CustomException("END");
            }

            if($goods_info['is_limit_buy'])
            {
                $where = [
                    'time'=> ['>', time()],
                    'customer_id'=> $param['customer_id'],
                    'goods_id'=> $param['goods_id']
                ];
                $count = db('limit_buy')->where($where)->count();
                if($count >= $goods_info['limit_buy_num'])
                {
                    throw new CustomException("LIMIT_NUM");
                }

                if($count)
                {
                    $time = db('limit_buy')->where($where)->value('time');
                }else{
                    if($goods_info['limit_buy_time'] == 0)
                    {
                        $time = 4294967295;
                    }else{
                        $time = time() + 86400*$goods_info['limit_buy_time'];
                    }

                }
            }

            $data = $this->goods([
                "num"=> $param['num'],
                "goods_id"=> $param['goods_id'],
                "customer_id"=> $param['customer_id']
            ]);

            $userInfo = Customer::where(['id'=> $param['customer_id']])->field('code, tiger_tee, money_xn as money')->find();
            if($data['is_limit'] && !$userInfo['code'])
            {
                throw new CustomException("CODE_IS_OK");
            }

            if($data['pay_tiger_tee'] > $userInfo['tiger_tee'])
            {
                throw new CustomException("TIGER_TEE_NOT_ENOUGH");
            }

            if($data['pay'] <= $userInfo['money'])
            {
                $status = 20;
                $use_money = 1;
            }else{
                $status = 10;
                $use_money = 0;
            }

            $order_no = Helper::createOrderSn();
            $serial_no = $order_no.rand(10000, 99999);

            $goods_insert = [
                "order_no"=> $order_no,
                "serial_no"=> $serial_no,
                "tiger_tee"=> $data['tiger_tee'],
                "price"=> $data['price'],
                "create_time"=> date('Y-m-d H:i:s'),
                "status"=> $status,
                "customer_id"=> $param['customer_id'],
                "fee"=> $data['fee'],
                "cover"=> $data['cover'],
                "num"=> $data['num'],
                "address"=> $data['address'],
                "goods_id"=> $data['goods_id'],
                "goods_name"=> $data['name'],
                "sponsor"=> $data['sponsor'],
                "pay_money"=> $data['pay'],
                "use_money"=> $use_money,
                "type"=> $data['type'],
                "coupon_id"=> $data['coupon_id'],
                "uid"=> $data['uid'],
                "add_money"=> $data['add_money'],
                "add_tiger"=> $data['add_tiger'],
                "tel"=> $param['tel'],
                "address2"=> $param['address2'],
            ];

            $o_id = Order::insertGetId($goods_insert);
            if($goods_info['is_limit_buy'])
            {
                db('limit_buy')->insert([
                    'customer_id'=> $param['customer_id'],
                    'goods_id'=> $param['goods_id'],
                    'time'=> $time
                ]);
            }
            if($use_money)
            {
                Customer::where(['id'=> $param['customer_id'], 'money_xn'=>['>=', $data['pay']]])->setDec('money_xn', $data['pay']);
                $coupon_ids = explode(',', $data['coupon_id']);

                $coupon = db('coupon')->where(['coupon_id'=> ['in', $coupon_ids]])->field('coupon_id, expired_type, expired_date, start_time, uid')->select();
                $post = [];
                foreach (range(1, $data['num']) as $value)
                {
                    foreach ($coupon as $v)
                    {
                        if($v['expired_type'] == 1){
                            $start_time = $v['start_time'];
                        }elseif($v['expired_type'] == 2){
                            $start_time = date('Y-m-d');
                        }
                        $end_time = date('Y-m-d', strtotime($start_time) + 86400*$v['expired_date']);
                        $post[] = [
                            'coupon_id'=> $v['coupon_id'],
                            'customer_id'=> $param['customer_id'],
                            'status'=> 1,
                            'start_time'=> $start_time,
                            'end_time'=> $end_time,
                            'uid'=> $v['uid'],
                            'o_id'=> $o_id,
                        ];
                    }
                }
                $code = db('customer')->where(['id'=> $param['customer_id']])->value('code');
                if($code)
                {
                    Customer::where(['id'=> $param['customer_id']])->setInc('money', $data['add_money']);
                    Customer::where(['id'=> $param['customer_id']])->setInc('tiger_tee', $data['add_tiger']);
                    if($data['add_money'] > 0 || $data['add_tiger'] > 0)
                    {
                        $unionid = db('customer')->where(['id'=> $param['customer_id']])->value('unionid');
                        $openid = db('customer')->where(['unionid'=> $unionid, 'type'=> 2])->value('openid');
                        $wx = new Wx();
                        if($data['add_money'] > 0 && $data['add_tiger'] <= 0)
                        {
                            MoneyLog::addLog([
                                "child_id"=> 0,
                                "u_id"=> $param['customer_id'],
                                "type"=> 1,
                                "value"=> $data['add_money'],
                                "reason_type"=> 13
                            ]);
                            $value = "恭喜您获得{$data['add_money']}元现金！！！";
                        }elseif ($data['add_tiger'] > 0 && $data['add_money'] <= 0){
                            MoneyLog::addLog([
                                "child_id"=> 0,
                                "u_id"=> $param['customer_id'],
                                "type"=> 2,
                                "value"=> $data['add_tiger'],
                                "reason_type"=> 14
                            ]);
                            $value = "恭喜您获得{$data['tiger_tee']}虎牙！！！";
                        }elseif ($data['add_money'] >0 && $data['add_tiger']>0){
                            MoneyLog::addLog([
                                "child_id"=> 0,
                                "u_id"=> $param['customer_id'],
                                "type"=> 1,
                                "value"=> $data['add_money'],
                                "reason_type"=> 13
                            ]);
                            MoneyLog::addLog([
                                "child_id"=> 0,
                                "u_id"=> $param['customer_id'],
                                "type"=> 2,
                                "value"=> $data['add_tiger'],
                                "reason_type"=> 14
                            ]);
                            $value = "恭喜您获得{$data['add_money']}元现金和{$data['add_tiger']}虎牙！！！";
                        }
                        $wx->sendTemplate([
                            'openid'=> $openid,
                            'template_id'=> 'KO7PzleBytwcD9tQ5bGixBdI7ewiSXIf_lM9az1JFWc',
                            'page'=> 'pages/mine/mine',
                            'data'=>[
                                "first"=> [
                                    "value"=> "您有收益到账了！！！",
                                ],
                                "keyword1"=> [
                                    "value"=> $value,
                            ],
                                "keyword2"=> [
                                    "value"=> date('Y-m-d H:i:s'),
                                ],
                            ]
                        ]);
                    }

                }else{
                    $parent_id = db('master_log')->where(['u_id'=> $param['customer_id']])->value('parent_id');
                    if($parent_id)
                    {
                        Customer::where(['id'=> $parent_id])->setInc('money', $data['add_money']);
                        Customer::where(['id'=> $parent_id])->setInc('tiger_tee', $data['add_tiger']);
                        if($data['add_money']>0 || $data['add_tiger']>0){
                            $unionid = db('customer')->where(['id'=> $parent_id])->value('unionid');
                            $openid = db('customer')->where(['unionid'=> $unionid, 'type'=> 2])->value('openid');
                            $wx = new Wx();
                            if($data['add_money']>0 && $data['add_tiger']<=0)
                            {
                                MoneyLog::addLog([
                                    "child_id"=> 0,
                                    "u_id"=> $param['customer_id'],
                                    "type"=> 1,
                                    "value"=> $data['add_money'],
                                    "reason_type"=> 13
                                ]);
                                $value = "恭喜您获得{$data['add_money']}元现金！！！";
                            }elseif ($data['add_tiger']>0 && $data['add_money']<=0){
                                MoneyLog::addLog([
                                    "child_id"=> 0,
                                    "u_id"=> $param['customer_id'],
                                    "type"=> 2,
                                    "value"=> $data['add_tiger'],
                                    "reason_type"=> 14
                                ]);
                                $value = "恭喜您获得{$data['tiger_tee']}虎牙！！！";
                            }elseif ($data['add_money']>0 && $data['add_tiger']>0){
                                MoneyLog::addLog([
                                    "child_id"=> 0,
                                    "u_id"=> $param['customer_id'],
                                    "type"=> 1,
                                    "value"=> $data['add_money'],
                                    "reason_type"=> 13
                                ]);
                                MoneyLog::addLog([
                                    "child_id"=> 0,
                                    "u_id"=> $param['customer_id'],
                                    "type"=> 2,
                                    "value"=> $data['add_tiger'],
                                    "reason_type"=> 14
                                ]);
                                $value = "恭喜您获得{$data['add_money']}元现金和{$data['add_tiger']}虎牙！！！";
                            }
                            $wx->sendTemplate([
                                'openid'=> $openid,
                                'template_id'=> 'KO7PzleBytwcD9tQ5bGixBdI7ewiSXIf_lM9az1JFWc',
                                'page'=> 'pages/mine/mine',
                                'data'=>[
                                    "first"=> [
                                        "value"=> "您有收益到账了！！！",
                                    ],
                                    "keyword1"=> [
                                        "value"=> $value,
                                    ],
                                    "keyword2"=> [
                                        "value"=> date('Y-m-d H:i:s'),
                                    ],
                                ]
                            ]);
                        }
                    }
                }

                MyCoupon::insertAll($post);
                Goods::where(['goods_id'=> $data['goods_id']])->setDec('num', $data['num']);
                Goods::where(['goods_id'=> $data['goods_id']])->setInc('sale_num', $data['num']);
                Customer::where(['id'=> $param['customer_id'], 'tiger_tee'=>['>=', $data['pay_tiger_tee']]])->setDec('tiger_tee', $data['pay_tiger_tee']);
            }

            $address_id = DeliveryAddress::where(['customer_id'=> $param['customer_id']])->value('id');
            if($address_id)
            {
                DeliveryAddress::where(['id'=> $address_id])->update([
                    'address'=> $param['address2'],
                    'tel'=> $param['tel']
                ]);
            }else{
                DeliveryAddress::insert([
                    'address'=> $param['address2'],
                    'tel'=> $param['tel'],
                    'customer_id'=> $param['customer_id']
                ]);
            }

            Db::commit();

        }catch (\Exception $exception){
//            echo $exception->getMessage();
            Db::rollback();
            throw new CustomException($exception->getMessage());

        }

        return [
            "serial_no"=> $serial_no,
            "total"=> $data["pay"],
            'use_money'=> $use_money,
            "o_id"=> $o_id
        ];


    }

    function getInfo($o_id)
    {
        $info = Order::where(['id'=> $o_id])->field('coupon_id, num')->find();
        $coupon_ids = explode(',', $info['coupon_id']);
        $num = sizeof($coupon_ids)*$info['num'];
        $data = MyCoupon::alias('m')
            ->join('coupon c', 'c.coupon_id = m.coupon_id')
            ->where(['m.coupon_id'=> ['in', $coupon_ids]])
            ->field('c.expired_type, c.coupon_id, c.name, m.start_time, m.end_time, c.expired_date, c.type, c.description, c.address, c.supermarket, c.value, c.code_url, c.condition, c.create_time, c.uid, m.id as my_coupon_id')
            ->order('m.id desc')
            ->limit($num)
            ->select();

        foreach ($data as &$v)
        {
            $create = date('Ymd', strtotime($v['create_time']));
            $v['quan_id'] = $create.$v['uid'].$v['my_coupon_id'];
        }
        return $data;

    }

    function myCoupon($uid, $status, $pageSize)
    {
        $where = [
            'm.customer_id'=> $uid
        ];
        $where2 = '';
        if($status)
        {
            $where['m.status'] = 1;
            $where['m.start_time'] = ['<=', date('Y-m-d')];
            $where['m.end_time'] = ['>=', date('Y-m-d')];
        }else{
            $where2 = "m.status = 2 or m.end_time < '".date('Y-m-d')."'";
        }

        $data = MyCoupon::alias('m')
            ->join('coupon c', 'c.coupon_id = m.coupon_id')
            ->where($where)
            ->where($where2)
            ->field('c.coupon_id, c.name, m.start_time, m.end_time, c.type, c.description, c.address, c.supermarket, c.value, c.code_url, c.condition, m.status,c.create_time, c.uid, m.id as my_coupon_id')
            ->order('m.id desc')
            ->paginate($pageSize)->each(function (&$item){
                if($item['status'] == 1 && $item['end_time'] < date('Y-m-d'))
                {
                    $item['status'] = 0;
                }
                $create = date('Ymd', strtotime($item['create_time']));
                $item['quan_id'] = $create.$item['uid'].$item['my_coupon_id'];
                return $item;
            });
        return $data;
    }

    function couponVerification($param)
    {
        $my_coupon = MyCoupon::where([
            'id'=> $param['my_coupon_id'],
            'customer_id'=> $param['customer_id']
        ])->field('id, coupon_id, customer_id, status, uid, start_time, end_time, o_id')->find();
        if(!$my_coupon)
        {
            throw new CustomException("COUPON_NOT_FIND");
        }
        if(strtotime($my_coupon['start_time']) <= time() && strtotime($my_coupon['end_time']) >= time())
        {
            if($my_coupon['status'] != 1){
                throw new CustomException("COUPON_USED");
            }
            $admin_ids = CompanyAdmin::where([
                'company_id'=> $my_coupon['uid']
            ])->column('customer_id');
            if(!in_array($param['u_id'], $admin_ids))
            {
                throw new CustomException("UNAUTHORIZED_OPERATION");
            }

            $time = date('Y-m-d H:i:s');
            $admin_name = db('customer')->where(['id'=> $param['u_id']])->value('nickname');
            MyCoupon::where(['id'=> $my_coupon['id']])->update(['status'=> 2, 'verify_time'=> $time, 'admin_name'=> $admin_name]);
            Order::where(['id'=> $my_coupon['o_id']])->update(['status'=> 30]);
            $user = Customer::where(['id'=> $my_coupon['customer_id']])->field('avatar_url, nickname')->find();
            $coupon = Coupon::where(['coupon_id'=> $my_coupon['coupon_id']])->field('name, num')->find();
            $count = MyCoupon::where(['coupon_id'=> $my_coupon['coupon_id']])->field('count(id) as num, status')->group('status')->select();
//            Log::writeLog(dump($count));
            $count = collection($count)->toArray();
            $count = array_column($count, 'num', 'status');
            return [
                'avatar_url'=> $user['avatar_url'],
                'nickname'=> $user['nickname'],
                'type'=> $coupon['name'],
                'verify_time'=> $time,
                'he'=> $count[2],
                'last'=> $coupon['num'] - $count[1] - $count[2]
            ];
        }else{
            throw new CustomException("COUPON_EXPIRED");
        }


    }


    function getCodeUrl($param)
    {
        $path = "packageA/pages/luckyDraw/verification/verification";
        return MIniprogram::createCodeImg3($path, http_build_query($param));
    }

    function lists($where){
        if(!$where['o.status'])
        {
            $where['o.status'] = ['>', 10];
        }

        if($where['o.status'] == 20)
        {
            $o_id = MyCoupon::where(['customer_id'=> $where['o.customer_id'], 'status'=> 1])->column('distinct o_id');
            $where['o.id'] = ['in', $o_id];
            $where['o.status'] = ['>', 10];
        }

        $orders = Order::alias('o')
            ->where($where)
            ->field('o.id, o.status, o.goods_name, o.cover, o.num, o.pay_money, o.order_no, o.use_money')
            ->order('o.id desc')
            ->paginate(15)->each(function (&$item){
                $coupon = MyCoupon::where(['o_id'=> $item['id']])->field('start_time, end_time')->find();
                $item['start_time'] = $coupon['start_time'];
                $item['end_time'] = $coupon['end_time'];
                return $item;
            });

        return $orders;
    }

    function orderDetail($where)
    {
        $data = Order::where($where)->field('id, cover, goods_name, coupon_id, pay_money, order_no, customer_id, create_time, goods_id')->find();
        if(!$data)
        {
            throw new CustomException("ORDER_NOT_FOUND");
        }
        $data['nickname'] = Customer::where(['id'=> $data['customer_id']])->value('nickname');
        $my = MyCoupon::where(['o_id'=> $data['id']])->field('start_time, end_time, status,id as my_coupon_id')->order('status')->select();
        if($my)
        {
            $my = collection($my)->toArray();
        }
        $data['start_time'] = $my[0]['start_time'];
        $data['end_time'] = $my[0]['end_time'];
        $coupon = Coupon::where(['coupon_id'=> $data['coupon_id']])->field('coupon_id, name, type, description, address, supermarket, value, code_url, condition, create_time, uid')->find();
        $create = date('Ymd', strtotime($coupon['create_time']));

        foreach ($my as &$v)
        {
            $v['coupon_id'] = $coupon['coupon_id'];
            $v['name'] = $coupon['name'];
            $v['type'] = $coupon['type'];
            $v['description'] = $coupon['description'];
            $v['address'] = $coupon['address'];
            $v['supermarket'] = $coupon['supermarket'];
            $v['value'] = $coupon['value'];
            $v['code_url'] = $coupon['code_url'];
            $v['condition'] = $coupon['condition'];
            $v['create_time'] = $coupon['create_time'];
            $v['uid'] = $coupon['uid'];


            if($v['status'] == 1 && $v['end_time'] < date('Y-m-d'))
            {
                $v['status'] = 0;
            }
            $v['quan_id'] = $create.$v['uid'].$v['my_coupon_id'];
        }
        $data['my_coupon'] = $my;

        $data['business'] = Goods::where(['goods_id'=> $data['goods_id']])->field('business_hours, business_tel, company_id')->find();
        $company = Company::where(['id'=> $data['business']['company_id']])->field('name, address')->find();
        $data['business']['name'] = $company['name'];
        $data['business']['address'] = $company['address'];

        return $data;

    }

    function evaluate($data, $u_id)
    {
        Db::startTrans();
        try{
            $order = Order::where(['id'=> $data['id']])->field('goods_id, is_prize, eval, status')->find();
            if(!$order)
            {
                throw new CustomException("ORDER_NOT_FOUND");
            }
            if($order['is_prize'])
            {
                throw new CustomException("PRIZE_HAS_GET");
            }
            if($order['status'] != 30)
            {
                throw new CustomException("USED_FIRST");
            }
            if($order['status'] == 40)
            {
                throw new CustomException("HAS_EVAL");
            }
            $data['status'] = 40;
            $data['is_prize'] = 1;
            Order::update($data);
            Customer::where(['id'=> $u_id])->setInc('redpacket_num');
            $goods = Goods::where(['goods_id'=> $order['goods_id']])->field('ticket_prize, tiger_tee_prize')->find();

            if ($goods['ticket_prize']) {
                $data2 = db('coupon')->where(['coupon_id'=> $goods['ticket_prize']])->field('name, expired_type, start_time, expired_date, uid')->find();
                if($data2['expired_type'] == 1)
                {
                    $post['start_time'] = $data2['start_time'];
                }else{
                    $post['start_time'] = date('Y-m-d');
                }
                $post['end_time'] = date('Y-m-d', strtotime($post['start_time']) + $data2['expired_date'] * 86400);
                $post['uid'] = $data2['uid'];
                $post['coupon_id'] = $goods['ticket_prize'];
                $post['customer_id'] = $u_id;
                db('my_coupon')->insert($post);
            }
            if($goods['tiger_tee_prize'])
            {
                Customer::where(['id'=> $u_id])->setInc('tiger_tee', $goods['tiger_tee_prize']);
            }
            Db::commit();

        }catch (Exception $exception){
            Db::rollback();
            throw new CustomException($exception->getMessage());
        }
    }

    function reward($where)
    {
        $goods_id = Order::where($where)->value('goods_id');
        $data = Goods::where(['goods_id'=> $goods_id])->field('ticket_prize, tiger_tee_prize')->find();
        $coupon = Coupon::where(['coupon_id'=> $data['ticket_prize']])->value('name');

        return [
            [
                'name'=> $coupon,
                'num'=> 1,
                'type'=> 2
            ],
            [
                'name'=> '虎牙',
                'num'=> $data['tiger_tee_prize'],
                'type'=> 3
            ]
        ];
    }

    function getPrize($data)
    {
        $result = [];
        $is_prize = 0;
        Db::startTrans();
        try
        {

            if($data['type'] == 1) // 随机红包
            {
                $redpacket_num = Customer::where(['id'=> $data['customer_id']])->value('redpacket_num');
                if($redpacket_num < 1)
                {
                    throw new CustomException("RED_NUM_BOT_ENOUGH");
                }
                $prize = Prize::where([])->field('id, name, type, value, number')->select();
                if($prize)
                {
                    $prize = collection($prize)->toArray();
                    $arr = [];
                    foreach ($prize as $vv)
                    {
                        $value = array_fill(0, $vv['number'], $vv['id']);
                        $arr = array_merge($arr, $value);
                    }
                    shuffle($arr);
                    shuffle($arr);
                    $key = mt_rand(0, sizeof($arr) - 1);
                    $key = $arr[$key];

                    foreach ($prize as $v)
                    {
                        if($key == $v['id'])
                        {
                            switch ($v['type'])
                            {
                                case 1:
                                    Customer::where(['id'=> $data['customer_id']])->setInc('money_xn', $v['value']);
                                    $user = Customer::where(['id'=> $data['customer_id']])->field('nickname, avatar_url')->find();
                                    PrizeLog::insert([
                                        'o_id'=> $data['o_id'],
                                        'prize_id'=> $v['id'],
                                        'nickname'=> $user['nickname'],
                                        'avatar_url'=> $user['avatar_url'],
                                        'prize_name'=> $v['name']."{$v['value']}元",
                                    ]);
                                    $result = [
                                        'name'=> $v['name'],
                                        'num'=> $v['value'],
                                        'type'=> 1
                                    ];
                                    break;
                                case 2:
                                    $data2 = db('coupon')->where(['coupon_id'=> $v['value']])->field('expired_type, start_time, expired_date, uid')->find();
                                    if($data2['expired_type'] == 1)
                                    {
                                        $post['start_time'] = $data2['start_time'];
                                    }else{
                                        $post['start_time'] = date('Y-m-d');
                                    }
                                    $post['end_time'] = date('Y-m-d', strtotime($post['start_time']) + $data2['expired_date'] * 86400);
                                    $post['uid'] = $data2['uid'];
                                    $post['coupon_id'] = $v['value'];
                                    $post['customer_id'] = $data['customer_id'];
                                    db('my_coupon')->insert($post);
                                    $user = Customer::where(['id'=> $data['customer_id']])->field('nickname, avatar_url')->find();
                                    PrizeLog::insert([
                                        'o_id'=> $data['o_id'],
                                        'prize_id'=> $v['id'],
                                        'nickname'=> $user['nickname'],
                                        'avatar_url'=> $user['avatar_url'],
                                        'prize_name'=> $v['name'].'一张',
                                    ]);
                                    $result = [
                                        'name'=> $v['name'],
                                        'num'=> "一张",
                                        'type'=> 2
                                    ];
                                    break;
                                case 3:
                                    Customer::where(['id'=> $data['customer_id']])->setInc('tiger_tee', $v['value']);
                                    $user = Customer::where(['id'=> $data['customer_id']])->field('nickname, avatar_url')->find();
                                    PrizeLog::insert([
                                        'o_id'=> $data['o_id'],
                                        'prize_id'=> $v['id'],
                                        'nickname'=> $user['nickname'],
                                        'avatar_url'=> $user['avatar_url'],
                                        'prize_name'=> $v['name']."{$v['value']}个",
                                    ]);
                                    $result = [
                                        'name'=> $v['name'],
                                        'num'=> "{$v['value']}个",
                                        'type'=> 3
                                    ];
                                    break;
                            }
                            $is_prize = 1;
                            break;
                        }
                    }

                    Customer::where(['id'=> $data['customer_id']])->setDec('redpacket_num');
                }
            }
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            throw new CustomException($exception->getMessage());
        }

        if(!$is_prize)
        {
            throw new CustomException("NO_PRIZE");
        }

        return $result;

    }

    function redPacket($data)
    {
        $count = Customer::where(['id'=> $data['customer_id']])->value('redpacket_num');
        $list = PrizeLog::where([])->field('nickname, avatar_url, prize_name')->order('id desc')->select();
        return [
            'list'=> $list,
            'count'=> $count
        ];
    }

    function refund($data)
    {
        Db::startTrans();
        try
        {
            $type = $data['type'];
            unset($data['type']);
            $order = Order::where($data)->field('id, trade_no, pay_money, status, customer_id')->find();
            if(!$order)
            {
                throw new CustomException("ORDER_NOT_FOUND");
            }
            if($order['status'] == 0)
            {
                throw new CustomException("ORDER_HAS_CANCEL");
            }
            if($order['status'] > 20)
            {
                throw new CustomException("ORDER_NOT_REFUND");
            }
            $out_refund_no = Helper::createOrderSn();
            if($type == 1) // 原路退回
            {
                if($order['trade_no'])
                {
                    $refund_fee = floor($order['pay_money']*100*0.8)/100;
                    $wx = new Wxpay();
                    $wx->refund([
                        'transaction_id'=> $order['trade_no'],
                        'out_refund_no'=> $out_refund_no,
                        'total_fee'=> $order['pay_money']*100,
                        'refund_fee'=> $refund_fee*100,
                    ]);
                }else {
                    throw new CustomException("YE");
                }
            }elseif ($type == 2){ //
                $refund_fee = $order['pay_money'];
                Customer::where(['id'=> $data['customer_id']])->setInc('money_xn', $refund_fee);
            }
            Order::where($data)->update([
                'out_refund_no'=> $out_refund_no,
                'refund_type'=> $type,
                'refund_fee'=> $refund_fee,
                'status'=> 0
            ]);
            MyCoupon::where(['customer_id'=> $order['customer_id'], 'o_id'=> $order['id']])->delete();

            Db::commit();

        }catch (Exception $exception){
            Db::rollback();
            throw new CustomException($exception->getMessage());
        }

        return true;

    }
}